package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.mapper.*;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.common.cache.GuiGuCache;
import com.atguigu.tingshu.model.album.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"all"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private BaseAttributeValueMapper baseAttributeValueMapper;
    @Autowired
    private BaseAttributeMapper baseAttributeMapper;

    @Override
    @GuiGuCache(prefix = "baseCategoryList")
    public List<JSONObject> getBaseCategoryList() {
        List<JSONObject> allCategoryList = new ArrayList<>();
        List<BaseCategoryView> allCategory = baseCategoryViewMapper.selectList(null);
        Map<Long, List<BaseCategoryView>> category1IdList = allCategory.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        if (CollectionUtil.isNotEmpty(category1IdList)) {
            for (Map.Entry<Long, List<BaseCategoryView>> entry1 : category1IdList.entrySet()) {
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("categoryId", entry1.getValue().get(0).getCategory1Id());
                jsonObject1.put("categoryName", entry1.getValue().get(0).getCategory1Name());
                List<JSONObject> jsonObject2List = new ArrayList<>();
                Map<Long, List<BaseCategoryView>> category2IdList = entry1.getValue().stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
                if (CollectionUtil.isNotEmpty(category2IdList)) {
                    for (Map.Entry<Long, List<BaseCategoryView>> entry2 : category2IdList.entrySet()) {
                        JSONObject jsonObject2 = new JSONObject();
                        jsonObject2.put("categoryId", entry1.getValue().get(0).getCategory2Id());
                        jsonObject2.put("categoryName", entry1.getValue().get(0).getCategory2Name());
                        List<JSONObject> jsonObject3List = new ArrayList<>();
                        if (entry2.getValue() != null) {
                            for (BaseCategoryView baseCategoryView : entry2.getValue()) {
                                JSONObject jsonObject3 = new JSONObject();
                                jsonObject3.put("categoryId", baseCategoryView.getCategory3Id());
                                jsonObject3.put("categoryName", baseCategoryView.getCategory3Name());
                                jsonObject3List.add(jsonObject3);
                            }
                        }
                        jsonObject2.put("categoryChild",jsonObject3List);
                        jsonObject2List.add(jsonObject2);
                    }
                }
                jsonObject1.put("categoryChild",jsonObject2List);
                allCategoryList.add(jsonObject1);

            }
        }
        return allCategoryList;
//		//1.创建目标集合对象
//		List<JSONObject> allList = new ArrayList<>();
//
//		//2.查询分类视图得到所有分类数据 共计401条记录
//		List<BaseCategoryView> allCategoryList = baseCategoryViewMapper.selectList(null);
//
//		//3.处理一级分类，对所有分类数据根据-根据一级分类ID分组
//		//3.1 采用Stream流进行集合分组，得到Map集合，Map中key:1级分类ID Map中Value：1级分类集合
//		Map<Long, List<BaseCategoryView>> category1Map =
//				allCategoryList.stream()
//						.collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
//		System.out.println(category1Map);
//		if (CollectionUtil.isNotEmpty(category1Map)) {
//			for (Map.Entry<Long, List<BaseCategoryView>> entry1 : category1Map.entrySet()) {
//				//每遍历一次处理一个一级分类
//				//3.2 获取一级分类ID 以及 名称
//				Long category1Id = entry1.getKey();
//				String category1Name = entry1.getValue().get(0).getCategory1Name();
//				//3.3 构建一级分类JSON对象
//				JSONObject jsonObject1 = new JSONObject();
//				jsonObject1.put("categoryId", category1Id);
//				jsonObject1.put("categoryName", category1Name);
//				//4.在某个一级分类内，处理二级分类，对一级分类集合根据二级分类ID分组
//				Map<Long, List<BaseCategoryView>> category2Map = entry1.getValue().stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
//				//4.2 对某个一级分类集合按照二级分类ID进行分组 得到二级分类Map Map-key 二级分类ID Map-Value 二级分类集合
//				if (CollectionUtil.isNotEmpty(category2Map)) {
//					List<JSONObject> jsonObject2List = new ArrayList<>();
//					for (Map.Entry<Long, List<BaseCategoryView>> entry2 : category2Map.entrySet()) {
//						//4.3 获取二级分类ID 以及 名称
//						Long category2Id = entry2.getKey();
//						String category2Name = entry2.getValue().get(0).getCategory2Name();
//						//4.4 遍历构建二级分类JSON对象 将二级分类对象加入到集合中
//						JSONObject jsonObject2 = new JSONObject();
//						jsonObject2.put("categoryId", category2Id);
//						jsonObject2.put("categoryName", category2Name);
//						//5.TODO 在某个二级分类内，处理三级分类
//						//5.1 遍历二级分类Map中Value
//						List<JSONObject> jsonObject3List = new ArrayList<>();
//						for (BaseCategoryView baseCategoryView : entry2.getValue()) {
//							//5.2 获取三级分类ID跟名称
//							Long category3Id = baseCategoryView.getCategory3Id();
//							String category3Name = baseCategoryView.getCategory3Name();
//							//5.3 构建三级分类JSON对象
//							JSONObject jsonObject3 = new JSONObject();
//							jsonObject3.put("categoryId", category3Id);
//							jsonObject3.put("categoryName", category3Name);
//							jsonObject3List.add(jsonObject3);
//						}
//						//5.4 将构建三级分类集合放入二级分类对象中"categoryChild"属性中
//						jsonObject2.put("categoryChild", jsonObject3List);
//						jsonObject2List.add(jsonObject2);
//					}
//					//4.5 将二级分类集合放入一级分类对象中"categoryChild"中
//					jsonObject1.put("categoryChild", jsonObject2List);
//				}
//				//3.4 将一级分类对象加入到所有目标集合对象中
//				allList.add(jsonObject1);
//			}
//		}
//		return allList;
    }

    @Override
    public List<BaseAttribute> getAttributesByCategory1Id(Long category1Id) {
        List<BaseAttribute> attributeList = baseAttributeMapper.selectList(new LambdaQueryWrapper<BaseAttribute>().eq(BaseAttribute::getCategory1Id,category1Id));
        for (BaseAttribute baseAttribute : attributeList) {
            List<BaseAttributeValue> baseAttributeValues = baseAttributeValueMapper.selectList(new LambdaQueryWrapper<BaseAttributeValue>().eq(BaseAttributeValue::getAttributeId, baseAttribute.getId()));
            baseAttribute.setAttributeValueList(baseAttributeValues);
        }
        return attributeList;
    }

    @Override
    public BaseCategoryView getCategoryViewBy3Id(Long category3Id) {
        BaseCategoryView baseCategoryView = baseCategoryViewMapper.selectOne(new LambdaQueryWrapper<BaseCategoryView>().eq(BaseCategoryView::getCategory3Id, category3Id));

        return baseCategoryView;
    }

    @Override
    public List<BaseCategory3> findTopBaseCategory3(Long category1Id) {
        //根据一级分类ID获取对应三级分类的数据集合
        //根据数据表结构 需要先获取对应2级分类ID集合再去查询到对应三级分类数据
        //并且三级分类数据只需要7个
        List<BaseCategory2> baseCategory2List = baseCategory2Mapper.selectList(new LambdaQueryWrapper<BaseCategory2>().eq(BaseCategory2::getCategory1Id, category1Id).select(BaseCategory2::getId));
        List<Long> category2Ids = baseCategory2List.stream().map(m -> m.getId()).collect(Collectors.toList());
        List<BaseCategory3> baseCategory3s = baseCategory3Mapper.selectList(new LambdaQueryWrapper<BaseCategory3>().in(BaseCategory3::getCategory2Id, category2Ids).last(" limit 7 ").orderBy(true,false,BaseCategory3::getOrderNum));
        for (BaseCategory3 baseCategory3 : baseCategory3s) {
            System.out.println(baseCategory3);
            System.out.println(baseCategory3.getId());
        }
        return baseCategory3s;
    }

    @Override
    public JSONObject getBaseCategoryListByCategory1Id(Long category1Id) {
        JSONObject jsonObject1 = new JSONObject();
        //获取与一级分类ID对应的所有分类数据
        List<BaseCategoryView> baseCategoryViews = baseCategoryViewMapper.selectList(new LambdaQueryWrapper<BaseCategoryView>().eq(BaseCategoryView::getCategory1Id, category1Id));
        Assert.notNull(baseCategoryViews,"查询一级分类数据失败");
        //根据二级分类ID进行分组
        Map<Long, List<BaseCategoryView>> category2Map = baseCategoryViews.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
        Assert.notNull(category2Map,"查询一级分类数据失败");
        jsonObject1.put("categoryName",baseCategoryViews.get(0).getCategory1Name());
        jsonObject1.put("categoryId",baseCategoryViews.get(0).getCategory1Id());

        //由二级分类ID进行循环

        List<JSONObject> list2 = new ArrayList<>();

        for (Map.Entry<Long, List<BaseCategoryView>> category2Entry : category2Map.entrySet()) {
            Assert.notNull(category2Entry,"查询一级分类数据失败");

            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("categoryName",category2Entry.getValue().get(0).getCategory2Name());
            jsonObject2.put("categoryId",category2Entry.getValue().get(0).getCategory2Id());
            List<JSONObject> list3 = new ArrayList<>();
            //拆解三级分类数据
            for (BaseCategoryView baseCategoryView : category2Entry.getValue()) {

                JSONObject jsonObject3 = new JSONObject();
                jsonObject3.put("categoryName",baseCategoryView.getCategory3Name());
                jsonObject3.put("categoryId",baseCategoryView.getCategory3Id());
                list3.add(jsonObject3);
            }
            jsonObject2.put("categoryChild",list3);
            list2.add(jsonObject2);
        }
        jsonObject1.put("categoryChild",list2);
        return jsonObject1;
    }

    @Override
    public List<Long> getAllCategory1() {
        List<BaseCategory1> baseCategory1s = baseCategory1Mapper.selectList(new LambdaQueryWrapper<BaseCategory1>().select(BaseCategory1::getId));
        Assert.notNull(baseCategory1s,"获取一级分类ID失败");
        List<Long> collect = baseCategory1s.stream().map(BaseCategory1::getId).collect(Collectors.toList());

        return collect;
    }
}
